﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Fiddler;

namespace CSharp.Libs.Net
{
    public class AmazonTagger
    {
        #region declarations
        private Proxy fpSecureEndpoint;
        List<Session> lstAllSessions = new List<Session>();

        private String strSecureEndpointHostname = "localhost";
        private string strSAZInfo = "NoSAZ";

        #region events
        #endregion
        #endregion



        #region constructor / terminator
        public AmazonTagger()
        {

            FiddlerApplication.Log.OnLogString += new EventHandler<LogEventArgs>(Log_OnLogString);
            FiddlerApplication.BeforeRequest += new SessionStateHandler(FiddlerApplication_BeforeRequest);
            FiddlerApplication.AfterSessionComplete += new SessionStateHandler(FiddlerApplication_AfterSessionComplete);

            FiddlerApplication.Log.LogString(String.Format("Starting {0} ({1})...", Fiddler.FiddlerApplication.GetVersionString(), strSAZInfo));

            CONFIG.IgnoreServerCertErrors = false;
            FiddlerApplication.Prefs.SetBoolPref("fiddler.network.streaming.abortifclientaborts", true);
            FiddlerCoreStartupFlags oFCSF = FiddlerCoreStartupFlags.Default;

            FiddlerApplication.Startup(80, oFCSF); //Start listening

            FiddlerApplication.Log.LogString("Starting with settings: [" + oFCSF + "]");
            FiddlerApplication.Log.LogString("Using Gateway: " + ((CONFIG.bForwardToGateway) ? "TRUE" : "FALSE"));
        }

        ~AmazonTagger()
        {
            //very important stop listening and remove proxy
            FiddlerApplication.Shutdown();
        }
        #endregion



        #region event handling
        /// <summary>FiddlerApplication_AfterSessionComplete</summary>
        /// <param name="oSession"></param>
        /// <remarks>executed after receiving a complete response</remarks>
        /// <history>24.07.2011</history>
        void FiddlerApplication_AfterSessionComplete(Session oSession)
        {
            FiddlerApplication.Log.LogString("FiddlerApplication_AfterSessionComplete: received URL: " + oSession.fullUrl);

            if(oSession.fullUrl.Contains("getChat.php"))
            {
                //String strTest = ByteArrayToString(oSession.GetResponseBodyAsString);
                String strTest = oSession.GetResponseBodyAsString();
                strTest = oSession.GetRequestBodyAsString();
            }
            //txtResult.Text = String.Concat(txtResult.Text, "Finished session:\t", oS.fullUrl, Environment.NewLine);

            //throw new NotImplementedException();
        }

        /// <summary>FiddlerApplication_BeforeRequest</summary>
        /// <param name="oSession"></param>
        /// <remarks>executed before sending a request</remarks>
        /// <history>24.07.2011</history>
        void FiddlerApplication_BeforeRequest(Session oSession)
        {
            if(oSession.fullUrl.Contains("amazon.de"))
            //if(oSession.fullUrl.Contains("192.168.2.90"))
            {
                const String AMAZONTAG = "tag=feuerware06-21";

                String strRequestBody = oSession.GetRequestBodyAsString();
                if(strRequestBody.ToLower().Contains("tag="))
                {
                    oSession.utilReplaceInRequest("tag=", "oldtag=");
                }

                if(oSession.PathAndQuery.ToLower().Contains("tag="))
                {
                    oSession.PathAndQuery = oSession.PathAndQuery.ToLower().Replace("tag=", "oldtag=");
                }

                if(!oSession.PathAndQuery.Contains("?"))
                {
                    oSession.PathAndQuery = string.Concat(oSession.PathAndQuery, "?", AMAZONTAG);
                }
                else
                {
                    oSession.PathAndQuery = string.Concat(oSession.PathAndQuery, "&", AMAZONTAG);
                }
            }
        }

        /// <summary>Log_OnLogString</summary>
        /// <param name="oSession"></param>
        /// <remarks>executed when receiving fiddler log entry</remarks>
        /// <history>24.07.2011</history>
        void Log_OnLogString(object sender, LogEventArgs e)
        {
            //txtResult.Text = String.Concat(txtResult.Text, "** LogString: " + oLEA.LogString, Environment.NewLine);
            //throw new NotImplementedException();
        }
        #endregion



        #region private functions
        private byte[] StringToByteArray(string str)
        {
            System.Text.ASCIIEncoding enc = new System.Text.ASCIIEncoding();
            return enc.GetBytes(str);
        }

        private string ByteArrayToString(byte[] arr)
        {
            System.Text.ASCIIEncoding enc = new System.Text.ASCIIEncoding();
            return enc.GetString(arr);
        }
        #endregion



        #region interface
        #region properties
        #endregion

        #region methods
        #endregion
        #endregion
    }
}
